#pragma once
#include "Socket.hpp"
#include <signal.h>
#include "Protocol.hpp"
#include <functional>
#include "log.hpp"  

using func_t = std::function<std::string(std::string& package)>;

class TcpServer
{
public:
  TcpServer(const uint16_t& port, func_t callback) : _port(port), _callback(callback)
  {
  }

  bool InitServer()
  {
    _listensock.Initsocket();
    _listensock.Bind(_port);
    _listensock.Listen();
    lg(Info, "InitServer done ....");
    return true;
  }

  void Start()
  {
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    lg(Info, "tcpServer is running.....");
    while (true)
    {
      std::string clientip;
      uint16_t clientport;
      int sockfd = _listensock.Accept(&clientip, &clientport);
      if (sockfd < 0) continue;
      lg(Info, "accpet a link ... sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
      // 子进程提供服务
      if (fork() == 0)
      {
        _listensock.Close();
        std::string inffer_stream;
        while (true)
        {
          char buffer[4096];
          // 读数据
          ssize_t n = read(sockfd, buffer, sizeof(buffer));
          if (n > 0)
          {
            buffer[n] = 0;
            inffer_stream += buffer;
            // std::cout << inffer_stream << std::endl;
            lg(Debug, "debug: %s\n", inffer_stream.c_str());
            while (true)
            {
              std::string info = _callback(inffer_stream);
              if (info.empty()) break;
              lg(Debug, "response : \n%s", info.c_str());
              lg(Debug, "debug: \n%s", inffer_stream.c_str());
              write(sockfd, info.c_str(), info.size());
            }

          }
          else if (n == 0)
          {
            break;
          }
          else
          {
            break;
          }
        }
        exit(0);
      }

      close(sockfd);
    }
  }

  ~TcpServer()
  {
  }

private:
  uint16_t _port;
  Socket _listensock;
  func_t _callback;
};